package com.market.cash.ui.presenter

import android.Manifest
import android.graphics.Color
import com.market.cash.R
import com.market.cash.pro.ProPresenter
import com.market.cash.ui.view.ICashRootPermissionView
import com.market.cash.utils.event.CashRootEventType
import com.market.cash.utils.helper.CashRootCustomConfigsHelper
import com.market.cash.utils.permission.OnPermissionCallback
import com.market.cash.utils.permission.XXPermissions
import org.json.JSONArray
import org.json.JSONObject

/**
 * CashRoot
 * @Author wwdeng
 * @CreateTime: 2024/9/4 15:41
 * @Annotation：权限页面
 */
class CashRootPermissionPresenter(private val iView: ICashRootPermissionView): ProPresenter(iView) {

    private var permissionList: ArrayList<JSONObject>? = null
    //当前权限下标
    private var curtIndex = 0

    /**
     * 获取权限列表
     */
    fun loadCashRootPermissionListAction(){
        permissionList = arrayListOf()
        val permissionArray = CashRootCustomConfigsHelper.getCashRootPermissionsLaunch()
        if (permissionArray != null){
            for (i in 0..<permissionArray.length()){
                val permission = permissionArray.optString(i)
                permissionList!!.add(formatCashRootPermissionItem(permission))
            }
        }
        iView.showPermissionList(permissionList!!)

        curtIndex = getCashRootPermissionIndex()
        setCashRootPermission()
    }

    /**
     * 下一个
     */
    fun onCashRootNextAction(){
        //全部同意
        if (isAgreeAll()){
            iView.showLoginPage()
            return
        }
        //全部完成（拒绝+同意） -> 展示拒绝的权限
        if (curtIndex == permissionList!!.size){
            iView.showPermissionPage(getCashRootPermissionIndex())
            return
        }
        curtIndex++
        iView.showPermissionPage(curtIndex)
    }

    /**
     * 拒绝权限
     */
    fun onCashRootDenyClick(){
        val item = permissionList!![curtIndex]
        item.put("isDeny",true)
        item.put("isClick",true)
        iView.showPermissionBanned()
        addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_PERMISSION_DENY,item.optString("permission"))

        onCashRootCheckPageClick(getCashRootPermissionIndex())
    }

    /**
     * 同意
     */
    fun onCashRootAgreeClick(){
        val item = permissionList!![curtIndex]
        hasRequestPermissions(item)

//        val tipsDialog = Dialog_Tips(iView.getAct(),item.optString("permission"),object : Dialog_Tips.IDialogCallback{
//            override fun onClick(view: View?) {
//                when(view!!.id){
//                    R.id.btn_ok -> {
//                        hasRequestPermissions(item)
//                        addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_PERMISSION_DIALOG_TIPS_OK,item.optString("permission"))
//                    }
//                    R.id.btn_cancel -> {
//                        addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_PERMISSION_DIALOG_TIPS_CANCEL,item.optString("permission"))
//                    }
//                }
//            }
//        })
//        tipsDialog.setCancelable(true)
//        tipsDialog.setCanceledOnTouchOutside(true)
//        tipsDialog.show()
//        tipsDialog.setTitleText(iView.getAct().getString(R.string.tips))
//        tipsDialog.setTipsText(iView.getAct().getString(R.string.permission_agree_tips))

        addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_PERMISSION_AGREE,item.optString("permission"))
    }

    /**
     * 切换Page
     */
    fun onCashRootCheckPageClick(index: Int){
        curtIndex = index
        setCashRootPermission()
    }

    /**
     * 已拒绝按钮
     */
    fun onCashRootBannedClick(){
        val item = permissionList!![curtIndex]
        XXPermissions.startPermissionActivity(iView.getAct(),item.optString("permission"))
        addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_PERMISSION_BANNED,item.optString("permission"))
    }

    /**
     * onResume
     */
    fun onCashRootPermissionResume(){
        curtIndex = getCashRootPermissionIndex()
        setCashRootPermission()
    }

    /**
     * 显示权限
     */
    private fun setCashRootPermission(){
        //全部允许
        if (isAgreeAll()){
            iView.showLoginPage()
            return
        }
        val item = permissionList!![curtIndex]
        iView.showPermissionPage(curtIndex)

        //是否已获得权限
        val isGranted = XXPermissions.isGranted(iView.getAct(),item.optString("permission"))
        //已获得权限
        if (isGranted){
            item.put("isDeny",false)
            item.put("isClick",true)
            iView.showPermissionAuthorized()
            return
        }
        if (item.optBoolean("isDeny",false)){
            iView.showPermissionBanned()
            return
        }
        iView.showPermissionNotObtained()
    }

    /**
     * 是否全部已授权
     */
    private fun isAgreeAll(): Boolean{
        var isAll = true
        if (permissionList!!.size > 0){
            for (i in 0..<permissionList!!.size){
                val item = permissionList!![i]
                //必须要申请的权限，需要判断申请状态
                if (item.optBoolean("isMust")){
                    if (!XXPermissions.isGranted(iView.getAct(),item.optString("permission"))){
                        isAll = false
                        break
                    }
                } else {//非必须权限，只需要判断点击状态
                    if (!item.optBoolean("isClick",false)){
                        isAll = false
                        break
                    }
                }
            }
        }
        return isAll
    }

    /**
     * 获取未授权的权限下标
     */
    private fun getCashRootPermissionIndex(): Int{
        var index = curtIndex
        if (permissionList!!.size > 0){
            for (i in 0..<permissionList!!.size){
                val item = permissionList!![i]
                //必须要申请的权限，需要判断申请状态
                if (item.optBoolean("isMust")){
                    if (!XXPermissions.isGranted(iView.getAct(),item.optString("permission")) && !item.optBoolean("isDeny",false)){
                        index = i
                        break
                    }
                } else {//非必须权限，只需要判断点击状态
                    if (!item.optBoolean("isClick",false)){
                        index = i
                        break
                    }
                }
            }
        }
        return index
    }

    /**
     * 获取所有权限列表
     */
    fun getCashRootPermissionList(): ArrayList<JSONObject>{
        return permissionList!!
    }

    /**
     * 申请权限
     */
    fun hasRequestPermissions(item: JSONObject){
        val permission = item.optString("permission")
        XXPermissions.with(iView.getAct())
            // 申请多个权限
            .permission(permission)
            .request(object: OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, p1: Boolean) {
                    if (p1){
                        item.put("isDeny",false)
                        item.put("isClick",true)
                        addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_PERMISSION_SYSTEM_AGREE,permission)
                        iView.showPermissionAuthorized()
                        //验证是否全部已同意
                        if (isAgreeAll()){
                            iView.showLoginPage()
                            return
                        }
                        curtIndex = getCashRootPermissionIndex()
                        setCashRootPermission()
                    }
                }
                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    item.put("isDeny",true)
                    item.put("isClick",true)
                    //不在询问
                    if (doNotAskAgain){
                        XXPermissions.startPermissionActivity(iView.getAct(),permission)
                        iView.showPermissionBanned()
                        return
                    }
                    addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_PERMISSION_SYSTEM_DENY,permission)
                    iView.showPermissionBanned()
                    //验证是否全部已同意
                    if (isAgreeAll()){
                        iView.showLoginPage()
                        return
                    }
                    curtIndex = getCashRootPermissionIndex()
                    setCashRootPermission()
                }
            })
    }

    /**
     * 拼装权限Item
     */
    private fun formatCashRootPermissionItem(permission: String): JSONObject{
        var item = JSONObject()
        item.put("permission",permission)
        item.put("isDeny",false)
        item.put("isClick",false)
        when(permission){
            Manifest.permission.READ_SMS -> {
                item.put("isMust",false)
                item.put("icon", R.mipmap.cash_permission)
                item.put("title",getString(R.string.permission_sms_title))
                item.put("titleColor", Color.parseColor("#FF222222"))

                val msgArray = JSONArray()
                val obj1 = JSONObject()
                obj1.put("title","")
                obj1.put("des",getString(R.string.permission_sms_desc))
                msgArray.put(obj1)

                item.put("msgList",msgArray)
            }
            Manifest.permission.READ_PHONE_STATE -> {
                item.put("isMust",true)
                item.put("icon",R.mipmap.cash_permission)
                item.put("title",getString(R.string.permission_phone_state_title))
                item.put("titleColor", Color.parseColor("#FF222222"))

                val msgArray = JSONArray()
                val obj1 = JSONObject()
                obj1.put("title","")
                obj1.put("des",getString(R.string.permission_phone_state_desc))
                msgArray.put(obj1)

                item.put("msgList",msgArray)
            }
        }
        return item
    }

}